package wjb.test.mawen.mawen.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import wjb.test.mawen.mawen.dto.AccessUser;
import wjb.test.mawen.mawen.dto.TokenInfo;
import wjb.test.mawen.mawen.mapper.UserMapper;
import wjb.test.mawen.mawen.model.User;
import wjb.test.mawen.mawen.provider.GiteeProvide;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class OAuthorizeController {

    @Autowired
    GiteeProvide giteeProvide;

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/callback")
    //第三方授权登录（码云）
    public String callBack(@RequestParam(name = "code") String code,
                           HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse){
        //get请求获取授权信息
        TokenInfo tokenInfo= giteeProvide.getAccessToken(code);
        //通过授权码，获取码云的用户信息
        AccessUser accessUser=giteeProvide.getUserInfo(tokenInfo.getAccess_token());

        if(accessUser !=null){
            //生成本地的用户信息
            String token = UUID.randomUUID().toString();
            User user=new User();
            user.setAccount_id(String.valueOf(accessUser.getId()));
            user.setName(accessUser.getName());
            user.setToken(token);
            user.setEmail(accessUser.getEmail());
            user.setGmt_create(System.currentTimeMillis());
            user.setGmt_modified(System.currentTimeMillis());
            //用户信息写回session，并在cookie中保存token
            httpServletRequest.getSession().setAttribute("user",user);
            httpServletResponse.addCookie(new Cookie("mawentoken",token));
            //用户信息保存到本系统的数据库
            userMapper.addUser(user);
            //重定向回首页
            String p= (String) httpServletRequest.getSession().getAttribute("currentpage");
            if(p !=null){
                httpServletRequest.getSession().removeAttribute("msg");
                return "redirect:/"+p;
            }
            return "redirect:/";
        }else{
            return "redirect:/";
        }

    }
}
